package com.learn.rabbitmq.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者 接收消息
 */
public class Cousumer {
    //队列名称
    public static final String QUEUE_NAME="hello";
    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //设置连接
        factory.setHost("127.0.0.1");
        factory.setUsername("admin");
        factory.setPassword("123");

        //建立连接
        Connection connection = factory.newConnection();
        //创建信道用于消息接收
        Channel channel = connection.createChannel();

        //声明 接收消息
        DeliverCallback deliverCallback=(consumerTag, message)->{
            //打印消息
            System.out.println(message);
            System.out.println(new String(message.getBody()));
        };

        //消费被取消或中断
        CancelCallback cancelCallback=consumerTag->{
            System.out.println("消息消费被中断");
        };
        /**
         * 消费者消费消息
         * 1.消费哪个队列
         * 2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
         * 3.消费者未成功消费的回调
         */
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }
}
